package com.pb.infra.auth.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.pb.infra.auth.entity.custom.PriviInterCustom;
import com.pb.infra.oth.util.*;
import com.pb.infra.oth.entity.common.Page;
import com.pb.infra.oth.entity.common.Result;
import com.pb.infra.auth.entity.custom.PriviMenuCustom;
import com.pb.infra.auth.entity.custom.PriviRoleCustom;
import com.pb.infra.auth.entity.pbsys.*;
import com.pb.infra.oth.exception.AppAuthException;
import com.pb.infra.oth.exception.ErrorCode;
import com.pb.infra.auth.mapper.custom.PriviUserCustomMapper;
import com.pb.infra.auth.mapper.pbsys.PriviPositionMapper;
import com.pb.infra.auth.mapper.pbsys.PriviPositionRoleMapper;
import com.pb.infra.auth.mapper.pbsys.PriviUserMapper;
import com.pb.infra.oth.service.SequenceGeneratorService;
import io.jsonwebtoken.Claims;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 用户管理
 *
 * @author liudebao
 * @date 2020/1/1
 */
@Service
public class PriviUserService {

    /**
     * 用户单表DAO映射
     */
    @Resource
    private PriviUserMapper userMapper;

    /**
     * 用户多表DAO映射
     */
    @Resource
    private PriviUserCustomMapper userCustomMapper;

    /**
     * 序号自动生成逻辑层
     */
    @Resource
    private SequenceGeneratorService sequenceGeneratorService;

    /**
     * 职位表DAO映射
     */
    @Resource
    private PriviPositionMapper priviPositionMapper;

    /**
     * 职位角色表DAO映射
     */
    @Resource
    private PriviPositionRoleMapper priviPositionRoleMapper;

    /**
     * jwttoken配置类
     */
    @Resource
    private JwtTokenConfig jwtTokenConfig;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 查询用户列表
     *
     * @param condition
     * @param page
     * @return
     */
    public Result select(Map<String, Object> condition, Page page, HttpServletRequest request) {
        if (!StringUtil.isEmpty(condition.get("loginUser")) && Constant.OK.equals(condition.get("loginUser").toString())) {
            String token = request.getHeader(jwtTokenConfig.getHeader());
            Claims claims = jwtTokenConfig.getClaimByToken(token);
            String userId = (String)claims.get(jwtTokenConfig.getSub());
            condition.put("loginUser", userId);
        }
        List<String> arrList = new ArrayList<>();
        condition.put("orgFlag", "");
        if (!StringUtil.isEmpty(condition.get("structId"))) {
            condition.put("orgFlag", "1");
            Map<String, Object> map = new HashMap<>();
            map.put("structId", condition.get("structId"));
            List<Map<String, Object>> list1 = userCustomMapper.selOrgId(map);
            if (list1 != null && list1.size() > 0) {
                arrList.add(list1.get(0).get("structId").toString());
                List<Map<String, Object>> list = userCustomMapper.selOrgByUpper(list1.get(0).get("structId").toString());
                arrList = getOrgIdByUpper(arrList, list);
            }
        }
        condition.put("arrList", arrList);
        if (page != null && page.getPageIndex() != null && page.getPageSize() != null) {
            PageHelper.startPage(page.getPageIndex(), page.getPageSize());
        }
        List<Map<String, Object>> list = userCustomMapper.select(condition);
        return Result.ok(new PageInfo(list).getTotal(), list);
    }

    /**
     * 递归组织架构
     * @param arrList
     * @param list1
     * @return
     */
    public List<String> getOrgIdByUpper(List<String> arrList, List<Map<String, Object>> list1) {
        if (list1 != null) {
            for (int i = 0; i < list1.size(); i++) {
                if (!StringUtil.isEmpty(list1.get(i).get("structId"))) {
                    arrList.add(list1.get(i).get("structId").toString());
                    List<Map<String, Object>> list = userCustomMapper.selOrgByUpper(list1.get(i).get("structId").toString());
                    arrList = getOrgIdByUpper(arrList, list);
                }
            }
        }
        return arrList;
    }

    /**
     *递归获取所有机构
     * @param arrList
     * @param list1
     */
    public List<String> getOrgId(List<String> arrList, List<Map<String, Object>> list1) {
        for (int i = 0; i < list1.size(); i++) {
            arrList.add(list1.get(i).get("structId").toString());
            Map<String, Object> map = new HashMap<>();
            map.put("structId", list1.get(i).get("structId").toString());
            List<Map<String, Object>> list2 = userCustomMapper.selOrgId(map);
            if (list2 != null && list2.size() > 0) {
                getOrgId(arrList,list2);
            }
        }
        return arrList;
    }

    /**
     * 新增用户信息
     *
     * @param map
     * @return
     */
    @Transactional
    public Map<String, Object> insert(Map<String, Object> map, HttpServletRequest request) {
        Map<String, Object> map2 = new HashMap<>();
        try {
            //校验用户编号重复
            List<Map<String, Object>> aList = userCustomMapper.selUserInfo(map);
            if (aList != null && aList.size() > 0) {
                if (!StringUtil.isEmpty(map.get("corpId")) && !StringUtil.isEmpty(map.get("selfCorp")) && !(map.get("corpId").toString()).equals(map.get("selfCorp").toString())) {
                    throw new AppAuthException(ErrorCode.ErrorCodeEnum.ACCESS_OTH_USER_KEY);
                } else {
                    throw new AppAuthException(ErrorCode.ErrorCodeEnum.ACCESS_USER_KEY);
                }
            }
            //不能使用超级管理员作为用户编号
            if (Constant.SYSTEM_ADMIN.equals(map.get("userId").toString()) || Constant.SYSTEM_ADMIN.equals(map.get("loginId").toString())) {
                throw new AppAuthException(ErrorCode.ErrorCodeEnum.ACCESS_SYS_ID);
            }
            if (StringUtil.isEmpty(map.get("userId"))) {
                throw new AppAuthException(ErrorCode.ErrorCodeEnum.ACCESS_USER_INFO);
            }
            String token = request.getHeader(jwtTokenConfig.getHeader());
            Claims claims = jwtTokenConfig.getClaimByToken(token);
            String userId = (String)claims.get(jwtTokenConfig.getSub());
            map.put("adminUser", userId);
            PriviUser use = new PriviUser();
            use.setUserId(map.get("userId").toString());
            use.setUserName(map.get("userName").toString());
            use.setLoginId(map.get("loginId").toString());
            use.setMobile(map.get("mobileNo").toString());
            use.setRemarks(map.get("remark").toString());
            use.setEmail(map.get("email").toString());
            //初始密码
            if (!StringUtil.isEmpty(Constant.USER_INIT_ASS)) {
                use.setPasswd(Constant.USER_INIT_ASS);
            }
            use.setUserSts(Constant.USER_STATE_ONE);
            use.setDeleteFlag(Constant.OK);
            use.setCreateUser(map.get("adminUser").toString());
            use.setCreateTime(DateTimeUtil.getStrFromNewDate());
            use.setUpdateUser(map.get("adminUser").toString());
            use.setUpdateTime(DateTimeUtil.getStrFromNewDate());
            String mainPositionId = "";
            //添加用户职位
            List<Map<String, Object>> list = (List<Map<String, Object>>)map.get("tableData");
            for (int i = 0; i < list.size(); i++) {
                Map<String, Object> map1 = list.get(i);
                String seqId = sequenceGeneratorService.getNextIdStr("POSITION", "POS");
                boolean v = (boolean) map1.get("mainPosition");
                if (v) {
                    mainPositionId = seqId;
                }
                PriviPosition priviPosition = new PriviPosition();
                priviPosition.setPositionId(seqId);
                priviPosition.setPositionName(map1.get("positionName").toString());
                priviPosition.setPostId(map1.get("postId").toString());
                priviPosition.setDeleteFlag(Constant.OK);
                if (!StringUtil.isEmpty(map1.get("lineId"))) {
                    priviPosition.setLineId(map1.get("lineId").toString());
                }
                priviPosition.setStructId(map1.get("structId").toString());
                if (!StringUtil.isEmpty(map1.get("deptId"))) {
                    priviPosition.setDeptId(map1.get("deptId").toString());
                }
                if (!StringUtil.isEmpty(map1.get("orgId"))) {
                    priviPosition.setOrgId(map1.get("orgId").toString());
                }
                priviPosition.setPositionSts(Constant.OK);
                priviPosition.setUserId(map.get("userId").toString());
                priviPosition.setCreateUser(map.get("adminUser").toString());
                priviPosition.setUpdateUser(map.get("adminUser").toString());
                priviPosition.setCreateTime(DateTimeUtil.getStrFromNewDate());
                priviPosition.setUpdateTime(DateTimeUtil.getStrFromNewDate());
                if (!StringUtil.isEmpty(map1.get("statStructId"))) {
                    priviPosition.setStatStructId(map1.get("statStructId").toString());
                }
                priviPosition.setDataRghtFlag(map1.get("dataRghtFlag").toString());
                priviPositionMapper.insertSelective(priviPosition);
                //添加职位对应角色
                if (!StringUtil.isEmpty(map1.get("roleId"))) {
                    /*List<String> roles = (List<String>) map1.get("roleId");
                    for (int j = 0; j < roles.size(); j++) {
                        PriviPositionRole priviPositionRole = new PriviPositionRole();
                        priviPositionRole.setRoleId(roles.get(j));
                        priviPositionRole.setPositionId(seqId);
                        priviPositionRole.setCreateUser(map.get("adminUser").toString());
                        priviPositionRole.setCreateTime(DateTimeUtil.getStrFromNewDate());
                        priviPositionRole.setUpdateTime(DateTimeUtil.getStrFromNewDate());
                        priviPositionRole.setUpdateUser(map.get("adminUser").toString());
                        priviPositionRoleMapper.insertSelective(priviPositionRole);
                    }*/
                    PriviPositionRole priviPositionRole = new PriviPositionRole();
                    priviPositionRole.setRoleId(map1.get("roleId").toString());
                    priviPositionRole.setPositionId(seqId);
                    priviPositionRole.setCreateUser(map.get("adminUser").toString());
                    priviPositionRole.setCreateTime(DateTimeUtil.getStrFromNewDate());
                    priviPositionRole.setUpdateTime(DateTimeUtil.getStrFromNewDate());
                    priviPositionRole.setUpdateUser(map.get("adminUser").toString());
                    priviPositionRoleMapper.insertSelective(priviPositionRole);
                }
            }

            List<Map<String, Object>> list1 = userCustomMapper.selMainPolicy(mainPositionId);
            if (list1 != null && list1.size() > 0) {
                use.setPasswdPolicyId(list1.get(0).get("pwdPolicyCd").toString()); // 密码策略
                if (!StringUtil.isEmpty(list1.get(0).get("activeDays"))) {
                    use.setPasswdExpiredTime(DateTimeUtil.getAddTime(Integer.parseInt(list1.get(0).get("activeDays").toString()))); // 密码过期时间
                }
                if (!StringUtil.isEmpty(list1.get(0).get("maxRetryTimes"))) {
                    use.setPasswdErrorTimes(new BigDecimal(Integer.parseInt(list1.get(0).get("maxRetryTimes").toString()))); // 密码错误次数
                }
            }
            use.setMainPositionId(mainPositionId);
            userMapper.insertSelective(use);
            map2.put("code", Constant.OK);
            map2.put("msg", Constant.INSERT_OK_MSG);
        } catch (AppAuthException e) {
            map2.put("msg", e.getMessage());
            map2.put("code", e.getCode());
        }
        return map2;
    }

    /**
     * 修改用户信息
     *
     * @param param
     * @return
     */
    @Transactional
    public Result update(Map<String, Object> param, HttpServletRequest request) {
        //是否修改密码策略
        if (!StringUtil.isEmpty(param.get("passFlag")) && Constant.EXIST.equals(param.get("passFlag").toString())) {
            Map<String, Object> map = new HashMap<>();
            map.put("passwdPolicyId", param.get("passwdPolicyId"));
            map.put("corpId", param.get("corpId"));
            List<Map<String, Object>> list = userCustomMapper.selPolicyData(map);
            if (list != null && list.size() > 0) {
                if (!StringUtil.isEmpty(list.get(0).get("activeDays"))) {
                    param.put("passwdExpiredTime", DateTimeUtil.getAddTime(Integer.parseInt(list.get(0).get("activeDays").toString())));
                    //user.setPasswdExpiredTime(DateTimeUtil.getAddTime(Integer.parseInt(list.get(0).get("activeDays").toString()))); // 密码过期时间
                }
                if (!StringUtil.isEmpty(list.get(0).get("maxRetryTimes"))) {
                    param.put("passwdErrorTimes", new BigDecimal(Integer.parseInt(list.get(0).get("maxRetryTimes").toString())));
                    //user.setPasswdErrorTimes(new BigDecimal(Integer.parseInt(list.get(0).get("maxRetryTimes").toString()))); // 密码错误次数
                }
            }
        }
        String token = request.getHeader(jwtTokenConfig.getHeader());
        Claims claims = jwtTokenConfig.getClaimByToken(token);
        String userId = (String)claims.get(jwtTokenConfig.getSub());
        param.put("updateTime", DateTimeUtil.getStrFromNewDate());
        param.put("updateUser", userId);
        userCustomMapper.updateUser(param);
        return Result.ok(userCustomMapper.selPolicyInfo(param.get("passwdPolicyId").toString()));
    }

    /**
     * 修改用户最后登录时间
     * @param user
     */
    public void updateLoginTime(PriviUser user) {
        userMapper.updateByPrimaryKeySelective(user);
    }

    /**
     * 删除用户
     *
     * @param user
     * @return
     */
    @Transactional
    public Result delete(PriviUser user) {
        if (!StringUtil.isEmpty(user.getUserSts())) {
            if (Constant.USER_NUMBER_ZERO.equals(user.getUserSts())) {
                user.setUserSts(Constant.USER_STATE_ONE);
            } else if (Constant.USER_NUMBER_ONE.equals(user.getUserSts())) {
                user.setUserSts(Constant.USER_STATE_TWO);
            } else if (Constant.USER_NUMBER_TWO.equals(user.getUserSts())) {
                user.setUserSts(Constant.USER_STATE_THREE);
            }
        }
        if (Constant.USER_NUMBER_ONE.equals(user.getDeleteFlag())) {
            PriviPosition priviPosition = new PriviPosition();
            priviPosition.setDeleteFlag(Constant.EXIST);
            PriviPositionExample priviPositionExample = new PriviPositionExample();
            PriviPositionExample.Criteria criteria = priviPositionExample.createCriteria();
            criteria.andUserIdEqualTo(user.getUserId());
            priviPositionMapper.updateByExampleSelective(priviPosition, priviPositionExample);
            userCustomMapper.updateStatus(user);
        } else if (Constant.USER_NUMBER_ZERO.equals(user.getDeleteFlag())) {
            List<Map<String, Object>> list = userCustomMapper.selPositionByUser(user.getUserId());
            if (list != null && list.size() > 0 && !StringUtil.isEmpty(list.get(0).get("deleteFlag")) && Constant.OK.equals(list.get(0).get("deleteFlag").toString())) {
                PriviPosition priviPosition = new PriviPosition();
                priviPosition.setDeleteFlag(Constant.OK);
                PriviPositionExample priviPositionExample = new PriviPositionExample();
                PriviPositionExample.Criteria criteria = priviPositionExample.createCriteria();
                criteria.andUserIdEqualTo(user.getUserId());
                criteria.andPositionIdEqualTo(list.get(0).get("positionId").toString());
                priviPositionMapper.updateByExampleSelective(priviPosition, priviPositionExample);
                userCustomMapper.updateStatus(user);
            } else {
                return Result.error("-1", "该用户对应的主职位的组织被删除，请修改");
            }
        } else {
            userCustomMapper.updateStatus(user);
        }
        return Result.OK_EMPTY;
    }

    /**
     *查询岗位
     * @param map
     * @return
     */
    public Result selPost(Map<String, Object> map) {
        return Result.ok(userCustomMapper.selectPost(map));
    }

    /**
     *查询条线
     * @param map
     * @return
     */
    public Result selectLine(Map<String, Object> map) {
        return Result.ok(userCustomMapper.selectLine(map));
    }

    /**
     *查询职位
     * @param map
     * @return
     */
    public Result selectPositionList(Map<String, Object> map) {
        return Result.ok(userCustomMapper.selectPosition(map));
    }

    /**
     *添加职位
     * @param map
     * @return
     */
    @Transactional
    public Map<String, Object> insertPosition(Map<String, Object> map, HttpServletRequest request) {
        Map<String, Object> map1 = new HashMap<>();
        try {
            List<Map<String, Object>> list = userCustomMapper.selPositionInfo(map);
            if (list != null && list.size() > 0) {
                throw new AppAuthException(ErrorCode.ErrorCodeEnum.ACCESS_TABLE_KEY);
            }
            String token = request.getHeader(jwtTokenConfig.getHeader());
            Claims claims = jwtTokenConfig.getClaimByToken(token);
            String updateUser = (String)claims.get(jwtTokenConfig.getSub());
            UserInfo userInfo = (UserInfo)redisTemplate.opsForValue().get(token);
            String seqId = sequenceGeneratorService.getNextIdStr("POSITION", "POS");
            boolean v = (boolean) map.get("mainPosition");
            if (v) {
                PriviUser priviUser = new PriviUser();
                priviUser.setUserId(map.get("userId").toString());
                priviUser.setMainPositionId(seqId);
                List<Map<String, Object>> list1 = userCustomMapper.selMainPolicy(seqId);
                if (list1 != null && list1.size() > 0) {
                    priviUser.setPasswdPolicyId(list1.get(0).get("pwdPolicyCd").toString()); // 密码策略
                    if (!StringUtil.isEmpty(list1.get(0).get("activeDays"))) {
                        priviUser.setPasswdExpiredTime(DateTimeUtil.getAddTime(Integer.parseInt(list1.get(0).get("activeDays").toString()))); // 密码过期时间
                    }
                    if (!StringUtil.isEmpty(list1.get(0).get("maxRetryTimes"))) {
                        priviUser.setPasswdErrorTimes(new BigDecimal(Integer.parseInt(list1.get(0).get("maxRetryTimes").toString()))); // 密码错误次数
                    }
                }
                userMapper.updateByPrimaryKeySelective(priviUser);
                List<Map<String, Object>> mapList = userCustomMapper.selMainPosition(updateUser);
                userInfo.setLogPosition(mapList);
                //redisTemplate.opsForValue().set(token + "logPosition", mapList, 24L, TimeUnit.HOURS);
            }
            PriviPosition priviPosition = new PriviPosition();
            priviPosition.setPositionId(seqId);
            priviPosition.setPositionName(map.get("positionName").toString());
            priviPosition.setPostId(map.get("postId").toString());
            priviPosition.setDeleteFlag(Constant.OK);
            if (!StringUtil.isEmpty(map.get("lineId"))) {
                priviPosition.setLineId(map.get("lineId").toString());
            }
            priviPosition.setStructId(map.get("structId").toString());
            if (!StringUtil.isEmpty(map.get("deptId"))) {
                priviPosition.setDeptId(map.get("deptId").toString());
            }
            if (!StringUtil.isEmpty(map.get("orgId"))) {
                priviPosition.setOrgId(map.get("orgId").toString());
            }
            priviPosition.setPositionSts(Constant.OK);
            priviPosition.setUserId(map.get("userId").toString());
            priviPosition.setCreateUser(updateUser);
            priviPosition.setUpdateUser(updateUser);
            priviPosition.setCreateTime(DateTimeUtil.getStrFromNewDate());
            priviPosition.setUpdateTime(DateTimeUtil.getStrFromNewDate());
            if (!StringUtil.isEmpty(map.get("statStructId"))) {
                priviPosition.setStatStructId(map.get("statStructId").toString());
            }
            priviPosition.setDataRghtFlag(map.get("dataRghtFlag").toString());
            priviPositionMapper.insertSelective(priviPosition);
            List<String> roles = (List<String>) map.get("roleId");
            for (int j = 0; j < roles.size(); j++) {
                PriviPositionRole priviPositionRole = new PriviPositionRole();
                priviPositionRole.setRoleId(roles.get(j));
                priviPositionRole.setPositionId(seqId);
                priviPositionRole.setCreateUser(updateUser);
                priviPositionRole.setUpdateUser(updateUser);
                priviPositionRole.setCreateTime(DateTimeUtil.getStrFromNewDate());
                priviPositionRole.setUpdateTime(DateTimeUtil.getStrFromNewDate());
                priviPositionRoleMapper.insertSelective(priviPositionRole);
            }
            /*if (!StringUtil.isEmpty(map.get("roleId"))) {
                PriviPositionRole priviPositionRole = new PriviPositionRole();
                priviPositionRole.setRoleId(map.get("roleId").toString());
                priviPositionRole.setPositionId(seqId);
                priviPositionRole.setCreateUser(updateUser);
                priviPositionRole.setUpdateUser(updateUser);
                priviPositionRole.setCreateTime(DateTimeUtil.getStrFromNewDate());
                priviPositionRole.setUpdateTime(DateTimeUtil.getStrFromNewDate());
                priviPositionRoleMapper.insertSelective(priviPositionRole);
            }*/
            List<PriviRoleCustom> roleList = userCustomMapper.selRoleByUserId(updateUser);
            userInfo.setUserRoles(roleList);
            if (redisTemplate.hasKey(token)) {
                redisTemplate.delete(token);
            }
            redisTemplate.opsForValue().set(token, userInfo, 24L, TimeUnit.HOURS);
            //redisTemplate.opsForValue().set(token + "userRoles", roleList, 24L, TimeUnit.HOURS);
            map1.put("code", Constant.OK);
            map1.put("msg", Constant.INSERT_OK_MSG);
        } catch (AppAuthException e) {
            map1.put("msg", e.getMessage());
            map1.put("code", e.getCode());
        }
        return map1;
    }

    /**
     *修改职位
     * @param map
     * @return
     */
    @Transactional
    public Map<String, Object> updatePosition(Map<String, Object> map, HttpServletRequest request) {
        Map<String, Object> map1 = new HashMap<>();
        try {
            if (!StringUtil.isEmpty(map.get("postFlag")) && Constant.EXIST.equals(map.get("postFlag").toString())) {
                List<Map<String, Object>> list = userCustomMapper.selPositionInfo(map);
                if (list != null && list.size() > 0) {
                    throw new AppAuthException(ErrorCode.ErrorCodeEnum.ACCESS_TABLE_KEY);
                }
            }
            String token = request.getHeader(jwtTokenConfig.getHeader());
            Claims claims = jwtTokenConfig.getClaimByToken(token);
            String updateUser = (String)claims.get(jwtTokenConfig.getSub());
            UserInfo userInfo = (UserInfo)redisTemplate.opsForValue().get(token);
            boolean v = (boolean) map.get("mainPosition");
            if (v) {
                PriviUser priviUser = new PriviUser();
                priviUser.setUserId(map.get("userId").toString());
                priviUser.setMainPositionId(map.get("positionId").toString());
                //redisTemplate.opsForValue().set(token + "logPosition", mapList, 24L, TimeUnit.HOURS);
                List<Map<String, Object>> list1 = userCustomMapper.selMainPolicy(map.get("positionId").toString());
                if (list1 != null && list1.size() > 0) {
                    priviUser.setPasswdPolicyId(list1.get(0).get("pwdPolicyCd").toString()); // 密码策略
                    if (!StringUtil.isEmpty(list1.get(0).get("activeDays"))) {
                        priviUser.setPasswdExpiredTime(DateTimeUtil.getAddTime(Integer.parseInt(list1.get(0).get("activeDays").toString()))); // 密码过期时间
                    }
                    if (!StringUtil.isEmpty(list1.get(0).get("maxRetryTimes"))) {
                        priviUser.setPasswdErrorTimes(new BigDecimal(Integer.parseInt(list1.get(0).get("maxRetryTimes").toString()))); // 密码错误次数
                    }
                }
                userMapper.updateByPrimaryKeySelective(priviUser);
                List<Map<String, Object>> mapList = userCustomMapper.selMainPosition(updateUser);
                userInfo.setLogPosition(mapList);
            }
            PriviPosition priviPosition = new PriviPosition();
            priviPosition.setPositionName(map.get("positionName").toString());
            priviPosition.setPostId(map.get("postId").toString());
            if (!StringUtil.isEmpty(map.get("lineId"))) {
                priviPosition.setLineId(map.get("lineId").toString());
            } else {
                priviPosition.setLineId("");
            }
            priviPosition.setPositionId(map.get("positionId").toString());
            priviPosition.setUpdateUser(updateUser);
            priviPosition.setUpdateTime(DateTimeUtil.getStrFromNewDate());
            if (!StringUtil.isEmpty(map.get("statStructId"))) {
                priviPosition.setStatStructId(map.get("statStructId").toString());
            } else {
                priviPosition.setStatStructId("");
            }
            priviPosition.setStructId(map.get("structId").toString());
            if (!StringUtil.isEmpty(map.get("deptId"))) {
                priviPosition.setDeptId(map.get("deptId").toString());
            } else {
                priviPosition.setDeptId("");
            }
            if (!StringUtil.isEmpty(map.get("orgId"))) {
                priviPosition.setOrgId(map.get("orgId").toString());
            } else {
                priviPosition.setOrgId("");
            }
            priviPosition.setDataRghtFlag(map.get("dataRghtFlag").toString());
            priviPositionMapper.updateByPrimaryKeySelective(priviPosition);
            PriviPositionRoleExample priviPositionRoleExample = new PriviPositionRoleExample();
            PriviPositionRoleExample.Criteria criteria = priviPositionRoleExample.createCriteria();
            criteria.andPositionIdEqualTo(map.get("positionId").toString());
            priviPositionRoleMapper.deleteByExample(priviPositionRoleExample);
            if (!StringUtil.isEmpty(map.get("roleId"))) {
                List<String> roles = (List<String>) map.get("roleId");
                for (int j = 0; j < roles.size(); j++) {
                    PriviPositionRole priviPositionRole = new PriviPositionRole();
                    priviPositionRole.setRoleId(roles.get(j));
                    priviPositionRole.setPositionId(map.get("positionId").toString());
                    priviPositionRole.setCreateUser(updateUser);
                    priviPositionRole.setCreateTime(DateTimeUtil.getStrFromNewDate());
                    priviPositionRole.setUpdateUser(updateUser);
                    priviPositionRole.setUpdateTime(DateTimeUtil.getStrFromNewDate());
                    priviPositionRoleMapper.insertSelective(priviPositionRole);
                }
                /*PriviPositionRole priviPositionRole = new PriviPositionRole();
                priviPositionRole.setRoleId(map.get("roleId").toString());
                priviPositionRole.setPositionId(map.get("positionId").toString());
                priviPositionRole.setCreateUser(updateUser);
                priviPositionRole.setCreateTime(DateTimeUtil.getStrFromNewDate());
                priviPositionRole.setUpdateUser(updateUser);
                priviPositionRole.setUpdateTime(DateTimeUtil.getStrFromNewDate());
                priviPositionRoleMapper.insertSelective(priviPositionRole);*/
            }
            List<PriviRoleCustom> roleList = userCustomMapper.selRoleByUserId(updateUser);
            userInfo.setUserRoles(roleList);
            if (redisTemplate.hasKey(token)) {
                redisTemplate.delete(token);
            }
            redisTemplate.opsForValue().set(token, userInfo, 24L, TimeUnit.HOURS);
            //redisTemplate.opsForValue().set(token + "userRoles", roleList, 24L, TimeUnit.HOURS);
            map1.put("code", Constant.OK);
            map1.put("msg", Constant.UPDATE_OK_MSG);
        } catch (AppAuthException e) {
            map1.put("msg", e.getMessage());
            map1.put("code", e.getCode());
        }
        return map1;
    }

    /**
     *查询密码策略
     * @param param
     * @return
     */
    public Result selPwdPolicy(Map<String, Object> param) {
        return Result.ok(userCustomMapper.selPwdPolicy(param));
    }

    /**
     *删除职位
     * @param map
     */
    @Transactional
    public void deletePosition(Map<String, Object> map) {
        userCustomMapper.updatePositionStatus(map);
    }

    /**
     *恢复职位
     * @param map
     */
    @Transactional
    public Result changePosition(Map<String, Object> map) {
        List<Map<String, Object>> list1 = userCustomMapper.selOrgByPosition(map);
        List<Map<String, Object>> list2 = userCustomMapper.selPostByPosition(map);
        if (list1 == null || list1.size() == 0) {
            return Result.error("-1", "该职位组织被删除，不能恢复");
        }
        if (list2 == null || list2.size() == 0) {
            return Result.error("-2", "该职位岗位被删除，不能恢复");
        }
        userCustomMapper.updatePositionStatus(map);
        return Result.OK_EMPTY;
    }

    /**
     *查询所有用户
     * @param param
     * @return
     */
    public List<Map<String, Object>> selAllUser(Map<String, Object> param, HttpServletRequest request) {
        if (!StringUtil.isEmpty(param.get("loginUser")) && Constant.OK.equals(param.get("loginUser").toString())) {
            String token = request.getHeader(jwtTokenConfig.getHeader());
            Claims claims = jwtTokenConfig.getClaimByToken(token);
            String userId = (String)claims.get(jwtTokenConfig.getSub());
            param.put("loginUser", userId);
        }
        List<String> arrList = new ArrayList<>();
        param.put("orgFlag", "");
        if (!StringUtil.isEmpty(param.get("structId"))) {
            param.put("orgFlag", "1");
            Map<String, Object> map = new HashMap<>();
            map.put("structId", param.get("structId"));
            List<Map<String, Object>> list1 = userCustomMapper.selOrgId(map);
            if (list1 != null && list1.size() > 0) {
                arrList.add(list1.get(0).get("structId").toString());
                List<Map<String, Object>> list = userCustomMapper.selOrgByUpper(list1.get(0).get("structId").toString());
                arrList = getOrgIdByUpper(arrList, list);
            } /*else {
                getOrgId(arrList, list1);
            }*/
            //condition.put("list", arrList);
        }
        Helper.supplementParamMap(param, "userId");
        Helper.supplementParamMap(param, "userName");
        Helper.supplementParamMap(param, "positionName");
        List<Map<String, Object>> list = userCustomMapper.select(param);
        List<Map<String, Object>> newList = new ArrayList<>();
        if (arrList.size() > 0 && list != null) {
            for (int i = 0; i < list.size(); i++) {
                if (!StringUtil.isEmpty(list.get(i).get("structId"))) {
                    String[] strings = list.get(i).get("structId").toString().split(",");
                    for (int j = 0; j < strings.length; j++) {
                        if (arrList.contains(strings[j])) {
                            newList.add(list.get(i));
                            break;
                        }
                    }
                }
            }
        } else {
            newList = list;
        }
         /*if (arrList.size() > 0 && list != null) {
             List<Map<String, Object>> newList = new ArrayList<>();
             for (int i = 0; i < list.size(); i++) {
                 if (!StringUtil.isEmpty(list.get(i).get("orgId"))) {
                     String[] strings = list.get(i).get("orgId").toString().split(",");
                     for (int j = 0; j < strings.length; j++) {
                         if(arrList.contains(strings[j])) {
                             newList.add(list.get(i));
                             break;
                         }
                     }
                 }
             }
             return Result.ok(new PageInfo(newList).getTotal(), newList);
         } else {
             return Result.ok(new PageInfo(list).getTotal(), list);
         }*/




        for (int i = 0; i < newList.size(); i++) {
            Map<String, Object> map = newList.get(i);
            if (map != null) {
                map.put("statusName", "正常");
                if ("1".equals(map.get("DELETED").toString())) {
                    map.put("statusName", "已删除");
                } else {
                    if (Constant.USER_STATE_TWO.equals(map.get("status").toString())) {
                        map.put("statusName", "自动锁定");
                    } else if (Constant.USER_STATE_THREE.equals(map.get("status").toString())) {
                        map.put("statusName", "手工锁定");
                    }
                }
            }
        }
        return newList;
    }

    /* *
     *查询主职位
     * @param userId
     * @return
     */
    public List<Map<String, Object>> selPosotion(String userId) {
        return  userCustomMapper.selMainPosition(userId);
    }

    /**
     *查询所有职位
     * @param map
     * @return
     */
    public Result selectAllPosition(Map<String, Object> map) {
        return Result.ok(userCustomMapper.selectAllPosition(map));
    }

    /**
     *重置密码
     * @param userList
     */
    @Transactional
    public void resetPasswd(List<String> userList) {
        Map<String, Object> map = new HashMap<>();
        map.put("passwd", Constant.USER_INIT_ASS);
        map.put("list", userList);
        userCustomMapper.resetPasswd(map);
        for (int i = 0; i < userList.size(); i++) {
            List<Map<String, Object>> list = userCustomMapper.selPolicy(userList.get(i));
            System.out.println(list);
            if (list != null && list.size() > 0 && list.get(0) != null) {
                PriviUser priviUser = new PriviUser();
                priviUser.setPasswdErrorTimes(new BigDecimal(Integer.parseInt(list.get(0).get("maxRetryTimes").toString())));
                priviUser.setPasswdExpiredTime(DateTimeUtil.getAddTime(Integer.parseInt(list.get(0).get("activeDays").toString())));
                PriviUserExample priviUserExample = new PriviUserExample();
                PriviUserExample.Criteria criteria = priviUserExample.createCriteria();
                criteria.andUserIdEqualTo(userList.get(i));
                userMapper.updateByExampleSelective(priviUser, priviUserExample);
            }
        }
    }

    /**
     * 用户角色信息
     * @param userId
     * @return
     */
    public List<PriviRoleCustom> selRoleByUserId(String userId) {
        return  userCustomMapper.selRoleByUserId(userId);
    }

    /**
     * 用户角色菜单
     * @param userId
     * @return
     */
    public List<PriviMenuCustom> selRoleMenuByUserId(String userId) {
        return  userCustomMapper.selRoleMenuByUserId(userId);
    }

    /**
     * 管理角色菜单
     * @param map
     * @return
     */
    public List<PriviInterCustom> selAdminRoleMenuByUserId(Map<String, Object> map) {
        return  userCustomMapper.selAdminRoleMenuByUserId(map);
    }

    /*public List<PriviMenuCustom> selectRoleMenu() {
        return  userCustomMapper.selectRoleMenu();
    }*/

    /**
     * 职位角色
     * @param map
     * @return
     */
    public List<PriviRoleCustom> selOtherRoleByUserId(Map<String, Object> map) {
        return  userCustomMapper.selOtherRoleByUserId(map);
    }

    /**
     * 多角色菜单
     * @param map
     * @return
     */
    public List<PriviInterCustom> selAdminRoleMenuByUserPosId(Map<String, Object> map) {
        return  userCustomMapper.selAdminRoleMenuByUserPosId(map);
    }

    /**
     * 多角色菜单
     * @param map
     * @return
     */
    public List<PriviMenuCustom> selRoleMenuByUserPosId(Map<String, Object> map) {
        return  userCustomMapper.selRoleMenuByUserPosId(map);
    }
    /*
    * 查询用户设备ID，消息推送
    *
    * */
    public List<String> selDeviceRegId(List<String> list) {
        return  userCustomMapper.selDeviceRegId(list);
    }

}
